/* beautify ignore:start */
import {provide, Directive} from '@angular/core';
import {Control, NG_VALIDATORS, Validator} from '@angular/common';
/* beautify ignore:end */

@Directive({
    selector: '[domain]',
    providers: [provide(NG_VALIDATORS, {useExisting: DomainValidator, multi: true})],
})

export class DomainValidator implements Validator {
    validate(c: Control): {[key: string]: any} {
        //var domainRegexp = /^(http(s)?:\/\/)?(www\.)?.[0-9a-z]([a-z0-9\-]*[a-z0-9])?\.(com|net|org|com.cn)$/;  
        var domainRegexp = /^[a-zA-Z0-9][-a-zA-Z0-9]{0,62}\.?([a-zA-Z0-9][-a-zA-Z0-9]{0,62})+\.(com|net|org|com.cn)$/;     
        var sDomainRegexp =  /^[0-9a-z]([a-z0-9\-]*[a-z0-9])?\.(com|net|org|com.cn)$/; 
        if(c.value && c.value.indexOf('.') == -1) {    
            return {'domain': true};    
        }
        if (c.value && !domainRegexp.test(c.value)) {        
            return {'domain': true};  
        }
        if (c.value && !sDomainRegexp.test(c.value)) {  
            return {'sdomain': true};    
        }  
    } 
} 
